//
//  VWPlayerNotReachableStateLayer.swift
//  VideoPlayer_Example
//
//  Created by JY_NEW on 2021/10/15.
//  Copyright © 2021 CocoaPods. All rights reserved.
//

import ijkPlayerManager
import UIKit
import UICreate

/// 网络状态
class VWPlayerNetworkStateLayer: VWPlayerBaseLayer {
    
    override var category: VideoPlayerLayerCategory {
        return .state
    }
    
    override var autoPause: Bool {
        return true
    }
    
    override func loadPlayerManager(_ player: VideoPlayerManagerType) {
        player.observer.networkStatus.addTarget( self, action: #selector(self.onStatusNetworkChanged))
        player.observer.status.addTarget( self, action: #selector(self.onStatusNetworkChanged))
    }
    override func unloadPlayerManager(_ player: VideoPlayerManagerType) {
        player.observer.networkStatus.removeTarget(self)
        player.observer.status.removeTarget(self)
    }
    
    override func loadContainerView(_ containerView: UIView) {
        containerView.backgroundColor = .black
        containerView.add(self.contentView, layout: .center)
    }
    
    @objc func onStatusNetworkChanged() {
        if let player = self.playerManager {
            ///可联网或离线视频直接取消
            if player.networkStatus.isReachable || (self.context?.isOffline ?? false) {
                if self.status.isActived {
                    self.deactive()
                }
                // 播放中且不可联网则激活
            }else if player.status.isBuffering || player.status.isError || player.status.isPaused {
                if !self.status.isActived {
                    self.active()
                }
            }
        }
    }
    
    override func show(completion: @escaping () -> Void) {
        self.aniamteShow(for: self.contentView, completion: completion)
    }
    override func hide(completion: @escaping () -> Void) {
        self.aniamteHide(for: self.contentView, completion: completion)
    }
    
    // MARK: 界面控件
    
    lazy var contentView: UIView = {
        let contentView = UIView()
        
        let image = UIImageView(.image("vw_play_network_error"))
        let title = UILabel(.text("网络出错，请检查网络"), .font(.pingfang(medium: 13)), .color(.white))
        let button = UIButton(.text("马上刷新"), .bg(.white), .size(68, 28), .corner(14), .font(.pingfang(12)), .color(.black), .event(self, #selector(self.onRetry)))
        contentView.add {
            image.layout(.top, .centerX)
            title.layout(.bottomTop(13), .for(.parent, .marginX))
            button.layout(.bottomTop(18), .centerX)
                .layout(for: .parent, .bottom)
        }
        
        return contentView
    }()
    @objc func onRetry() {
        self.deactive()
        self.playerManager?.play()
    }
}
